# -*- coding: utf-8 -*-
"""
---------------------------------------
@File    ：adsl_call.py
@Author  ：liyunhui
@Date    ：2024/9/16 上午9:30 
@explain : 文件说明
---------------------------------------
"""
import paramiko
import traceback


def server_dial(server_info, intranet_ip, logging):
    """
    云服务器发送拨号任务
    :param server_info: 拨号云服务器信息
    :param intranet_ip: 内网IP
    :param logging: 日志模块
    :return:
    """
    script_path = '/lyh/restart_adsl_and_call_api.sh'
    server_ip = server_info.get('ip')
    server_port = server_info.get('port')
    username = server_info.get('user')
    password = server_info.get('password')
    # 创建 SSH 客户端
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        # 连接到服务器
        ssh_client.connect(hostname=server_ip, username=username, password=password, port=server_port)
        # 执行脚本
        stdin, stdout, stderr = ssh_client.exec_command(f'bash {script_path}')
        # 获取执行结果
        result = stdout.read().decode('utf-8')
        error = stderr.read().decode('utf-8')
        # 如果有错误信息，返回错误信息
        if error:
            logging.error(f"云主机内网IP: {intranet_ip} ---- 远程执行异常: {server_ip} --- {error}")
        else:
            logging.info(f"云主机内网IP: {intranet_ip} ---- 远程执行拨号成功: {server_ip}")
        # 返回脚本执行结果
        return result
    except Exception as e:
        error_message = traceback.format_exc()  # 获取完整的异常堆栈信息
        logging.error(f"云主机内网IP: {intranet_ip} ---- 远程重启拨号异常: {server_ip} error: {error_message}")
        return f"SSH connection failed: {str(e)}"

    finally:
        # 关闭 SSH 连接
        ssh_client.close()
